package reserve
import (
    "time"
	"strings"
	"errors"
	"dhfshop/models"
	"github.com/astaxie/beego/orm"
)

//可预约项目类型
type SchemaType struct {
    SchemaTypeId int64     `orm:"column(schema_type_id);pk;auto" json:"schema_type_id" form:"schema_type_id"` //
	PartnerId    int64       `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`              //
	StoreId      int64       `orm:"column(store_id)" json:"store_id" form:"store_id"`
	Name         string    `orm:"column(name)" json:"name" form:"name"`                                //类型名称
	CreatedAt    time.Time `orm:"auto_now_add;column(created_at);type(datetime)" json:"created_at" form:"-"` //创建时间
	UpdatedAt    time.Time `orm:"auto_now;column(updated_at);type(datetime)" json:"updated_at" form:"-"`     //修改时间
}

func init() {
	orm.RegisterModel(new(SchemaType))
}

func AddSchemaType(m *SchemaType) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func AddMultiSchemaTypes(list []*SchemaType) (err error) {
	size := len(list)
	o := models.GetDefaultDB()
	if size > 1 {
	    _, err = o.InsertMulti(size, list) 
	}else{
	   _, err = o.Insert(list[0])
	}
	return
}

func GetSchemaTypeById(id int64) (v *SchemaType, err error) {
	o := models.GetDefaultDB()
	v = &SchemaType{SchemaTypeId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}
//查询所有餐桌
func GetAllSchemaTypes(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*SchemaType, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(SchemaType))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	var lists []*SchemaType
	qs = qs.OrderBy(sortFields...)
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}
func UpdateSchemaTypeById(m *SchemaType, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := SchemaType{SchemaTypeId: m.SchemaTypeId}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}
func DeleteSchemaType(id int64) (err error) {
	o := models.GetDefaultDB()
	v := SchemaType{SchemaTypeId: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

